package com.wanggsx.library.util;

import android.app.Activity;
import android.content.DialogInterface;
import androidx.appcompat.app.AlertDialog;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.RelativeLayout;

import com.wang.avi.AVLoadingIndicatorView;
import com.wanggsx.library.R;

public class UtilsDialog {
    /**
     * 加载框实例
     */
    private static AlertDialog mLoadingDilog;
    private static AVLoadingIndicatorView mIndicatorView;
    private static Activity mLastContext;

    /**
     * 显示加载框
     */
    public static void showLoading(Activity activity) {
        showLoading(activity, false);
    }

    public static void showLoading(Activity activity, boolean isCanceledOnTouchOutside) {
        showLoading(activity, isCanceledOnTouchOutside, true);
    }

    public static void showLoading(Activity activity, boolean isCanceledOnTouchOutside, boolean isCancelable) {
        closeLoading();
        mLastContext = activity;
        mLoadingDilog = new AlertDialog.Builder(mLastContext, R.style.MyTransparentTheme).create();
        View view = LayoutInflater.from(mLastContext).inflate(R.layout.dialog_loading, null, false);
        ViewGroup.LayoutParams params = view.getLayoutParams();
        if (params == null) {
            params = new RelativeLayout.LayoutParams(UtilsScreen.getScreenWidth(), UtilsScreen.getScreenHeight());
            view.setLayoutParams(params);
        } else {
            params.width = UtilsScreen.getScreenWidth();
            params.height = UtilsScreen.getScreenHeight();
        }
        mIndicatorView = view.findViewById(R.id.avliview_dialog_loading);
        mLoadingDilog.setCanceledOnTouchOutside(isCanceledOnTouchOutside);
        mLoadingDilog.setCancelable(isCancelable);
        mLoadingDilog.setOnKeyListener(new DialogInterface.OnKeyListener() {
            @Override
            public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
                    closeLoading();
                    return true;
                }
                return false;
            }
        });
        mLoadingDilog.getWindow().setDimAmount(0);
        mLoadingDilog.show();
        mLoadingDilog.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
        mLoadingDilog.setContentView(view);
        mIndicatorView.smoothToShow();
    }

    /**
     * 关闭加载框
     */
    public static void closeLoading() {
        if (mLastContext != null && !mLastContext.isFinishing() && mLoadingDilog != null) {
            mIndicatorView.hide();
            mLoadingDilog.dismiss();
            mIndicatorView = null;
            mLoadingDilog = null;
        } else {
            mLastContext = null;
            mLoadingDilog = null;
            mIndicatorView = null;
        }
    }

}
